import React, { useRef } from 'react';
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  Radio,
  DatePicker,
  AutoComplete,
  TreeSelect,
  notification,
  Upload,
} from 'antd';
import { cptUpload } from '@/services/pay';
import { connect } from 'dva';

const { Option } = Select;
const { TextArea } = Input;

export interface isProps {
  auth?: any;
  form?: any;
  mode?: string; // view 、 edit 、add
  close?: () => void;
  submit?: (view: any, data: any) => void;
  disabled?: boolean;
  personData?: any;
  commodityData?: any;
  utilsData?: any;
  dispatch?: (action: any) => void;
}

export default class Index extends React.Component<isProps, any> {
  static defaultPros = {
    disabled: false,
    auth: {},
  };
  state = {
    photourl: '',
    clientHeight: 200,
  };

  componentDidMount() {
    let height = document.body.clientHeight;
    this.setState({
      clientHeight: Number(height) * 0.7,
    });
  }

  handleSubmit = () => {
    const { close, submit, auth } = this.props;
    const { photourl } = this.state;
    this.props.form.validateFieldsAndScroll((err: any, values: any) => {
      if (!err) {
        close && close();
        const data = { ...values, proofPhotoUrl: photourl };
        submit && submit(auth, data);
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { disabled, personData, commodityData, utilsData } = this.props;

    const { photourl, clientHeight } = this.state;
    const selectAfter = getFieldDecorator('unit')(
      <Select style={{ width: 95 }}>
        {utilsData.map((item: any, index: number) => {
          return (
            <Option value={item.value} key={item.label}>
              {item.label}
            </Option>
          );
        })}
      </Select>,
    );
    const uploadButton = (
      <div>
        <Icon type={'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const proofPhotoUrl = this.props.form.getFieldValue('proofPhotoUrl');
    return (
      <Form
        {...formItemLayout}
        onSubmit={this.handleSubmit}
        style={{ height: `${clientHeight}px`, overflowY: 'scroll' }}
      >
        <Form.Item label={'商品名'}>
          {getFieldDecorator('wineId', {
            rules: [{ required: true, message: '请输入商品' }],
          })(
            <Select
              showSearch
              placeholder="请输入商品"
              filterOption={false}
              disabled={disabled}
              onSearch={(value: any) => {
                const { dispatch } = this.props;
                if (dispatch) {
                  dispatch({
                    type: 'order/commoditySearch',
                    payload: { comments: value },
                  });
                }
              }}
              onChange={val => {
                const { dispatch } = this.props;
                if (dispatch) {
                  dispatch({
                    type: 'order/instockSpec',
                    payload: {
                      id: val,
                    },
                  });
                }
              }}
            >
              {commodityData.length > 0
                ? commodityData.map((item: any) => (
                    <Option value={item.id}>
                      {item.name}（{item.comments}）
                    </Option>
                  ))
                : null}
            </Select>,
          )}
        </Form.Item>
        <Form.Item label="付款人">
          {getFieldDecorator('payer', {
            rules: [
              {
                required: true,
              },
            ],
          })(
            <Input type="text" disabled={disabled} placeholder="请输入付款人" />,
            // <Select
            //   showSearch
            //   disabled={disabled}
            //   placeholder="请输入工作人员"
            //   filterOption={false}
            //   onChange={() => {}}
            // >
            //   {personData.length > 0
            //     ? personData.map((item: any) => (
            //         <Option value={item.id}>
            //           {item.name} （{item.phoneNumber}）
            //         </Option>
            //       ))
            //     : null}
            // </Select>,
          )}
        </Form.Item>
        <Form.Item label="收款人">
          {getFieldDecorator('payee', {
            rules: [
              {
                required: true,
              },
            ],
          })(
            <Input type="text" disabled={disabled} placeholder="请输入收款人" />,
            // <Select
            //   showSearch
            //   disabled={disabled}
            //   placeholder="请输入工作人员"
            //   filterOption={false}
            //   onChange={() => {}}
            // >
            //   {personData.length > 0
            //     ? personData.map((item: any) => (
            //         <Option value={item.id}>
            //           {item.name} （{item.phoneNumber}）
            //         </Option>
            //       ))
            //     : null}
            // </Select>,
          )}
        </Form.Item>
        <Form.Item label={'数量'}>
          {getFieldDecorator('qty', {
            rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入正确的数量' }],
          })(<Input placeholder="请输入数量" disabled={disabled} addonAfter={selectAfter} />)}
        </Form.Item>
        <Form.Item label="付款金额">
          {getFieldDecorator('payAmount', {
            rules: [
              {
                required: true,
                message: '请输入付款金额',
              },
            ],
          })(<Input type="number" disabled={disabled} prefix="￥" suffix="RMB" />)}
        </Form.Item>
        <Form.Item label="付款时间">
          {getFieldDecorator('dealTime', {
            rules: [{ required: true, message: '请选择付款时间' }],
          })(<DatePicker disabled={disabled} />)}
        </Form.Item>
        <Form.Item label={'上传凭证'}>
          {getFieldDecorator('proofPhotoUrl')(
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              accept="image/*"
              customRequest={async (info: any) => {
                try {
                  const file = info.file;
                  let form = new FormData();
                  form.append('file', file);
                  const { dispatch } = this.props;
                  const res: any = await cptUpload(form);
                  if (res.status == 200) {
                    notification.success({
                      message: '上传成功',
                      description: '',
                    });
                    const path = res.data.path.replace('127.0.0.1', 'http://115.28.136.118');
                    this.setState({
                      photourl: path,
                    });
                  }
                } catch (error) {}
              }}
            >
              {/* {proofPhotoUrl ? (
                <img src={proofPhotoUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )} */}
              {photourl ? (
                <img src={photourl} alt="avatar" style={{ width: '100%' }} />
              ) : proofPhotoUrl ? (
                <img src={proofPhotoUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>,
          )}
        </Form.Item>
        <Form.Item label={'备注'}>
          {getFieldDecorator('comments')(<TextArea disabled={disabled} rows={4} />)}
        </Form.Item>
      </Form>
    );
  }
}
